package loader;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import au.com.bytecode.opencsv.CSVReader;

/**
 * 	Load the data from CSV file.
 * 
 *	@author Yexi Jiang <http://users.cis.fiu.edu/~yjian004/>
 *	@date 2011-8-26
 */
public class CSVLoader {
	
	private String filepath;
	
	private String regInteger = "[0-9]+";	//	integer regular pattern
	private String regFloat = "[0-9]+\\.[0-9]+";	//	float regulaar pattern
	private Pattern patInteger = Pattern.compile(regInteger);
	private Pattern patFloat = Pattern.compile(regFloat);
	
	public CSVLoader(String filepath){
		this.filepath = filepath;
	}
	
	public List<Map<String, Object>> loadData() throws IOException{
		List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
		CSVReader reader = new CSVReader(new FileReader(filepath));
	    String[] featureName = reader.readNext();
	    
	    String[] nextLine;
	    while((nextLine = reader.readNext()) != null){
	    	Map<String, Object> record = new HashMap<String, Object>();
	    	for(int i = 0; i < nextLine.length; ++i){
	    		String feature = nextLine[i];
	    		Object realValue = convert(feature);
	    		record.put(featureName[i], realValue);
	    	}
	    	records.add(record);
	    }
	    
		return records;
	}
	
	/**
	 * Parse the input string and return its real type: integer, float or string
	 * @param str
	 * @return
	 */
	private Object convert(String str){
		Object realValue = null;
		
		try{
			realValue = Integer.parseInt(str);
		} catch(NumberFormatException nfe){
			try{
				realValue = Float.parseFloat(str);
			} catch(NumberFormatException e){
			}
		}
		return realValue;
	}
}
